<template>
  <view class="home">
    <!-- prescription -->
    <!-- 头部 start -->
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      leftBtnShow="true"
      :backgroundImage="backgroundImage"
      :border="false"
      leftIcon="back"
      color="#fff"
      @clickLeft="clickLeft"
    >
      <view class="uni-title">{{ title }}</view>
    </uni-nav-bar>
    <!-- 头部 end -->
    <view class="map_box" v-if="chufangInfo.status == '110'">
      <map
        id="navi_map"
        :longitude="endLocation.longitude"
        :latitude="endLocation.latitude"
        scale="11"
        :markers="markers"
        :polyline="polyline"
      ></map>
    </view>
    <view
      :class="[
        chufangInfo.status == '110' ? 'innerBox1' : 'innerBox2',
        'innerBox',
      ]"
    >
      <view class="desInner">
        <view class="title"
          >配送单号<view
            class="icon iconfont icon-zidongduibishuomingshu"
          ></view>
        </view>
        <view>{{ deliveryInfo.orderId || "暂无" }}</view>
        <view
          v-if="chufangInfo.status"
          class="status"
          :class="'status' + chufangInfo.status"
          >{{ orderStatusLabel(chufangInfo.status) }}</view
        >
      </view>
      <view class="desInner hospInner" v-if="chufangInfo.status == '110'">
        <view class="zIndex1000">
          <view class="title"
            >冷链箱<view
              class="icon iconfont icon---lenglianyingfufapiaobaozhangdan"
            ></view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">冷链箱编号:</view>
            <view class="infoRight">{{ chufangInfo.boxCode }}</view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">环境状态:</view>
            <view class="infoRight" style="display: flex">
              <view
                :class="
                  boxInfo.temperature >= boxInfotemperature.min &&
                  boxInfo.temperature <= boxInfotemperature.max
                    ? 'successBox'
                    : 'errorBox'
                "
                >{{
                  boxInfo.temperature >= boxInfotemperature.min &&
                  boxInfo.temperature <= boxInfotemperature.max
                    ? "温度正常"
                    : "温度异常"
                }}</view
              >
              <view
                :class="
                  boxInfo.humidity >= boxInfoHumidity.min &&
                  boxInfo.humidity <= boxInfoHumidity.max
                    ? 'successBox'
                    : 'errorBox'
                "
                >{{
                  boxInfo.humidity >= boxInfoHumidity.min &&
                  boxInfo.humidity <= boxInfoHumidity.max
                    ? "湿度正常"
                    : "湿度异常"
                }}</view
              >
            </view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">温度:</view>
            <view class="infoRight">
              <view
                :style="{
                  color:
                    boxInfo.temperature >= boxInfotemperature.min &&
                    boxInfo.temperature <= boxInfotemperature.max
                      ? '#009688'
                      : 'red',
                  fontWeight: 600,
                  fontSize: '30rpx',
                }"
              >
                {{ boxInfo.temperature }}℃<span
                  style="font-size: 12px; color: #999; font-weight: 400"
                  >（ 适宜温度 为2到8摄氏度 ）</span
                >
              </view>
            </view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">湿度:</view>
            <view class="infoRight">
              <view
                :style="{
                  color:
                    boxInfo.humidity >= boxInfoHumidity.min &&
                    boxInfo.humidity <= boxInfoHumidity.max
                      ? '#009688'
                      : 'red',
                  fontWeight: 600,
                  fontSize: '30rpx',
                }"
              >
                {{ boxInfo.humidity }}%rh<span
                  style="font-size: 12px; color: #999; font-weight: 400"
                  >（ 适宜湿度 为百分35到75 ）</span
                >
              </view>
            </view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">开启状态:</view>
            <view class="infoRight">中途无打开</view>
          </view>
        </view>
        <view class="bgInner">
          <image src="../../static/image/lenglian.png" />
        </view>
      </view>
      <view class="desInner hospInner">
        <view class="zIndex1000">
          <view class="title">
            药店
            <view class="icon iconfont icon-sf-stor"></view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">配送药店:</view>
            <view class="infoRight">{{ deliveryInfo.drugstoreName|| "暂无"  }}</view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">配送人员:</view>
            <view class="infoRight">{{
              deliveryInfo.deliveryPeople || "暂无"
            }}</view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">手机号:</view>
            <view class="infoRight">
              <view @click="call_phone">{{
                deliveryInfo.deliveryPhone || "暂无"
              }}</view>
            </view>
          </view>
        </view>
        <view class="bgInner">
          <image src="../../static/image/store.png" />
        </view>
      </view>
      <view class="desInner hospInner">
        <view class="zIndex1000">
          <view class="title"
            >医院<view class="icon iconfont icon-toububeijingyiyuan"></view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">医院:</view>
            <view class="infoRight">{{ chufangInfo.hospitalName }}</view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">诊断:</view>
            <view class="infoRight">{{ chufangInfo.diagnoseName }}</view>
          </view>
          <view class="infoBox">
            <view class="infoLeft">药品名称及数量:</view>
          </view>
          <view class="infoBox" style="height: auto">
            <view class="infoRight">
              <view v-if="chufangInfo.isBack">
                <view
                  v-for="(item, index) in chufangInfo.prescriptionDetails"
                  :key="index"
                  style="
                    display: flex;
                    border-bottom: 1px solid #d3d1d1;
                    padding: 10rpx 0;
                    display: flex;
                    justify-content: space-between;
                  "
                  :class="!item.isBack ? 'isAccept' : 'isNotAccept'"
                >
                  <view style="flex: 1; display: flex">
                    <view>{{ item.drugTradeName || item.drugGenericName }}</view
                    >/
                    <view>{{ item.numBack }}/{{ item.amount }}</view>
                  </view>
                  <view v-if="!item.isBack">
                    <view
                      class="icon iconfont icon-yiqianshou1 isAcceptIcon"
                    ></view>
                  </view>
                </view>
              </view>
              <view v-else>
                <view
                  v-for="(item, index) in chufangInfo.prescriptionDetails"
                  :key="index"
                  style="
                    display: flex;
                    border-bottom: 1px solid #d3d1d1;
                    padding: 10rpx 0;
                    display: flex;
                    justify-content: space-between;
                  "
                  :class="!item.isBack ? 'isAccept' : 'isNotAccept'"
                >
                  <view style="flex: 1; display: flex">
                    <view>{{ item.drugTradeName || item.drugGenericName }}</view
                    >/
                    <view>{{ item.numBack }}/{{ item.amount }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="bgInner">
          <image src="../../static/image/hosp.png" />
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import moment from "@/static/js/moment";
import hccmStore from "@/common/hccm-store.js";
var amapFile = require("@/static/js/amap/amap-wx.js");
const utilMd5 = require("@/static/js/md5.js");
var config = require("@/static/js/amap/config.js");
import mRequest from "@/api/home";
import hccmConfig from "@/common/hccm-config.js";
import dict from "@/static/js/dict.json";
export default {
  data() {
    return {
      chufangInfo: {},
      deliveryInfo: {}, // 配送相关信息
      orderId: "",
      boxInfo: {},
      boxInfoHumidity: {
        min: 35,
        max: 75,
      },
      boxInfotemperature: {
        min: 2,
        max: 8,
      },
      markers: [],
      distance: "",
      endLocation: {
        latitude: 41.775945,
        longitude: 123.453414,
      },
      cost: "",
      EXPRESS_PHATRMACY: hccmConfig.EXPRESS_PHATRMACY,
      EXPRESS_PERSON: hccmConfig.EXPRESS_PERSON,
      EXPRESS_PHONE: hccmConfig.EXPRESS_PHONE,
      polyline: [],
      // 41.774479
    };
  },
  computed: {
    title() {
      return "针剂详情";
    },
    backgroundImage() {
      return this.status === 0
        ? "linear-gradient(#3388FF, #6197f8)"
        : "linear-gradient(#2D67F0, #3388FF)";
    },
  },
  onLoad() {
    this.chufangInfo = hccmStore.getInjectionInfo();
    console.log(this.chufangInfo);
    // this.chufangInfo.status = '110'
    this.orderId = this.chufangInfo.orderIdZj;
    this.getOrderZj();
    this.realTimeMeterData();
    // return
  },
  onShow() {},
  methods: {
    moment(val) {
      return moment(val).format("YYYY-MM-DD HH:mm:ss");
    },
    isLocationOutOfChina(latitude, longitude) {
      if (
        longitude < 72.004 ||
        longitude > 137.8347 ||
        latitude < 0.8293 ||
        latitude > 55.8271
      )
        return true;
      return false;
    },
    transformLatWithXY(x, y) {
      var pi = 3.14159265358979324;
      var lat =
        -100.0 +
        2.0 * x +
        3.0 * y +
        0.2 * y * y +
        0.1 * x * y +
        0.2 * Math.sqrt(Math.abs(x));
      lat +=
        ((20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) *
          2.0) /
        3.0;
      lat +=
        ((20.0 * Math.sin(y * pi) + 40.0 * Math.sin((y / 3.0) * pi)) * 2.0) /
        3.0;
      lat +=
        ((160.0 * Math.sin((y / 12.0) * pi) + 320 * Math.sin((y * pi) / 30.0)) *
          2.0) /
        3.0;
      return lat;
    },

    transformLonWithXY(x, y) {
      var pi = 3.14159265358979324;
      var lon =
        300.0 +
        x +
        2.0 * y +
        0.1 * x * x +
        0.1 * x * y +
        0.1 * Math.sqrt(Math.abs(x));
      lon +=
        ((20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) *
          2.0) /
        3.0;
      lon +=
        ((20.0 * Math.sin(x * pi) + 40.0 * Math.sin((x / 3.0) * pi)) * 2.0) /
        3.0;
      lon +=
        ((150.0 * Math.sin((x / 12.0) * pi) +
          300.0 * Math.sin((x / 30.0) * pi)) *
          2.0) /
        3.0;
      return lon;
    },
    transformLonWithXY(x, y) {
      var pi = 3.14159265358979324;
      var lon =
        300.0 +
        x +
        2.0 * y +
        0.1 * x * x +
        0.1 * x * y +
        0.1 * Math.sqrt(Math.abs(x));
      lon +=
        ((20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) *
          2.0) /
        3.0;
      lon +=
        ((20.0 * Math.sin(x * pi) + 40.0 * Math.sin((x / 3.0) * pi)) * 2.0) /
        3.0;
      lon +=
        ((150.0 * Math.sin((x / 12.0) * pi) +
          300.0 * Math.sin((x / 30.0) * pi)) *
          2.0) /
        3.0;
      return lon;
    },
    /**
     *  将WGS-84(国际标准)转为GCJ-02(火星坐标):
     */
    transformFromWGSToGCJ(latitude, longitude) {
      var lat = "";
      var lon = "";
      var ee = 0.00669342162296594323;
      var a = 6378245.0;
      var pi = 3.14159265358979324;

      if (this.isLocationOutOfChina(latitude, longitude)) {
        lat = latitude;
        lon = longitude;
      } else {
        var adjustLat = this.transformLatWithXY(
          longitude - 105.0,
          latitude - 35.0
        );
        var adjustLon = this.transformLonWithXY(
          longitude - 105.0,
          latitude - 35.0
        );
        var radLat = (latitude / 180.0) * pi;
        var magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        var sqrtMagic = Math.sqrt(magic);
        adjustLat =
          (adjustLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * pi);
        adjustLon =
          (adjustLon * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * pi);
        latitude = latitude + adjustLat;
        longitude = longitude + adjustLon;
      }
      return { latitude: latitude, longitude: longitude };
    },

    // 经纬度转换
    locationsChange(str) {
      console.log(str);
      let that = this;
      wx.request({
        url: `https://restapi.amap.com/v3/assistant/coordinate/convert?key=${config.Config.key}&locations=${str}&coordsys=gps`, //str = 123.445404,41.771366   gps药店：123.441452,41.772289
        data: {},
        method: "GET", // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        success: function (res) {
          // success
          console.log(res, "wahahha");
          that.boxInfo.lng = res.data.locations.split(",")[0];
          that.boxInfo.lat = res.data.locations.split(",")[1];
          that.boxInfo.lat = String(
            Number(that.boxInfo.lat) - 0.0026980347230036728
          );
          that.boxInfo.lng = String(
            Number(that.boxInfo.lng) - 0.0033195876739995356
          );
          that.markers = [
            {
              iconPath: "../../static/image/amap/mapicon_now.png",
              id: 1,
              // latitude: '41.776748',
              // longitude: '123.45378',
              latitude: that.boxInfo.lat,
              longitude: that.boxInfo.lng,
              width: 33,
              height: 33,
            },
            {
              iconPath: "../../static/image/amap/mapicon_navi_s.png",
              id: 2,
              latitude: "41.774407",
              longitude: "123.450355",
              width: 24,
              height: 34,
              title: "药店",
            },
            {
              iconPath: "../../static/image/amap/mapicon_navi_e.png",
              id: 3,
              latitude: that.endLocation.latitude,
              longitude: that.endLocation.longitude,
              width: 24,
              height: 34,
            },
          ];
        },
        fail: function () {
          // fail
        },
        complete: function () {
          // complete
        },
      });
    },
    // 返回
    clickLeft() {
      uni.navigateBack();
    },

    // 龙邦实时数据
    realTimeMeterData() {
      let aaa = {
        customerCode: hccmConfig.VUE_APP_CUSTOMER_CODE, //客户编码 （213456051472583713）
        companyCode: hccmConfig.VUE_APP_COMPANY_CODE, //企业编码 （677161524077857076）
        hostCode: String(this.chufangInfo.boxCode), //主机编码  （730030300012）
        // hostCode: "730030300012", //主机编码
      };
      // 序列化
      var res = Object.keys(aaa).sort();
      // bbb为key=value的字符串
      var bbb = "";
      for (var key in res) {
        bbb += `${res[key]}=${aaa[res[key]]}&`;
      }
      // 然后需要加上 企业密钥 VUE_APP_SIGN （eddf18641489496e846a302e2cce744b） 之后进行Md5加密
      bbb = utilMd5.hexMD5(
        bbb.slice(0, bbb.length - 1) + hccmConfig.VUE_APP_SIGN
      );
      console.log(bbb);
      // params是参数
      let params = {
        sysParam: {
          sign: bbb, // 业务参数签名
        },
        busParam: aaa,
      };
      // console.log(params);
      mRequest.realTimeMeterData(params).then((res) => {
        this.boxInfo = res.data[0];
        let aaa = this.transformFromWGSToGCJ(
          Number(this.boxInfo.lat),
          Number(this.boxInfo.lng)
        );
        // let aaa = this.transformFromWGSToGCJ(Number(this.boxInfo.lat), Number(this.boxInfo.lng))
        this.locationsChange(`${aaa.longitude},${aaa.latitude}`);
        // this.getMap()
      });
    },

    // getMap
    getMap() {
      var that = this;
      var key = config.Config.key;
      var myAmapFun = new amapFile.AMapWX({ key: key });
      myAmapFun.getDrivingRoute({
        origin: `${this.boxInfo.lng},${this.boxInfo.lat}`,
        destination: `${this.endLocation.longitude},${this.endLocation.latitude}`,
        success: function (data) {
          var points = [];
          if (data.paths && data.paths[0] && data.paths[0].steps) {
            var steps = data.paths[0].steps;
            for (var i = 0; i < steps.length; i++) {
              var poLen = steps[i].polyline.split(";");
              for (var j = 0; j < poLen.length; j++) {
                points.push({
                  longitude: parseFloat(poLen[j].split(",")[0]),
                  latitude: parseFloat(poLen[j].split(",")[1]),
                });
              }
            }
          }
          that.polyline = [
            {
              points: points,
              color: "#0091ff",
              width: 6,
            },
          ];
        },
      });
    },
    orderStatusLabel(val) {
      return dict.injectionStatusList.filter((item) => {
        return val == item.value;
      })[0].label;
    },

    // 针剂详情
    getOrderZj() {
      mRequest.getOrderZj({ orderId: this.orderId }).then((res) => {
        this.deliveryInfo = res.responseData;
      });
    },
  },
};
</script>

<style lang="scss">
@import "@/static/css/index.scss";

// begin
.home {
  height: 100%;
  overflow: hidden;

  .map_box {
    position: absolute;
    top: 88px;
    height: 600rpx;
    left: 0px;
    right: 0px;
  }

  #navi_map {
    width: 100%;
    height: 100%;
  }

  .text_box {
    position: absolute;
    height: 90px;
    bottom: 0px;
    left: 0px;
    right: 0px;
  }

  .text_box .text {
    margin: 15px;
  }

  .detail_button {
    position: absolute;
    bottom: 30px;
    right: 10px;
    padding: 3px 5px;
    color: #fff;
    background: #0091ff;
    width: 50px;
    text-align: center;
    border-radius: 5px;
  }

  .innerBox {
    margin: 600rpx 30rpx 30rpx;

    .desInner {
      margin-bottom: 20rpx;
      border-radius: 6rpx;
      background: #fff;
      padding: 20rpx 30rpx 30rpx;
      position: relative;

      .status {
        position: absolute;
        right: 0rpx;
        top: 26rpx;
        font-size: 26rpx;
        color: #fff;
        padding: 10rpx 20rpx 10rpx 36rpx;
        border-radius: 30rpx 0 0 30rpx;
      }

      .title {
        position: relative;
        font-weight: 600;
        font-size: 34rpx;
        height: 50rpx;
        line-height: 50rpx;
        display: flex;
        margin-bottom: 20rpx;

        .iconfont {
          color: #0091ff;
          margin-left: 18rpx;
          font-weight: 600;
        }
      }

      .title:before {
        content: "";
        position: absolute;
        left: -15rpx;
        top: 21%;
        height: 60%;
        background: #0091ff;
        width: 6rpx;
        border-radius: 6rpx;
      }

      .infoBox {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        font-size: 32rpx;
        color: #333;
        height: 50rpx;

        .infoLeft {
          // width: 180rpx;
          color: #666;
          display: flex;
          justify-content: flex-end;
          padding-right: 20rpx;
          font-weight: 400;
        }

        .infoRight {
          flex: 1;
        }
      }

      .bgInner {
        position: absolute;
        bottom: 20rpx;
        right: 20rpx;
        z-index: 10;
        height: 140rpx;
        width: 100%;
        display: flex;
        justify-content: flex-end;

        image {
          height: 140rpx;
          width: 140rpx;
          opacity: 0.2;
        }
      }
    }

    .hospInner {
      min-height: 300rpx;
    }
  }

  .innerBox2 {
    margin: 30rpx 30rpx 30rpx !important;
  }

  .zIndex1000 {
    z-index: 1000;
  }

  .successBox {
    background: rgba($color: #009688ed, $alpha: 0.7);
    border-radius: 6rpx;
    color: #fff;
    font-size: 26rpx;
    padding: 4rpx 10rpx;
    margin-right: 10rpx;
  }

  .errorBox {
    background: rgba($color: red, $alpha: 0.7);
    border-radius: 6rpx;
    color: #fff;
    font-size: 26rpx;
    padding: 4rpx 10rpx;
    margin-right: 10rpx;
  }

  .isAccept {
    color: #999;

    .isAcceptIcon {
      color: #999;
    }
  }

  .isNotAccept {
    color: #0091ff;
  }
}
</style>
